//
//  JQNetworkManager.m
//  JQNetworking
//
//  Created by zhujiaquan on 2018/1/10.
//  Copyright © 2018年 JQ. All rights reserved.
//

#import "JQNetworkManager.h"
#import "JQNetworkConfig.h"
#import "JQNetworkLog.h"

@interface JQNetworkManager ()

+ (AFHTTPSessionManager *)createHTTPSessionManagerWithConfiguration:(JQNetworkConfigBlock)configurationBlock;

@end


@implementation JQNetworkManager

#pragma mark - Public Methods
+ (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters
                 configuration:(JQNetworkConfigBlock)configurationBlock
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [JQNetworkManager createHTTPSessionManagerWithConfiguration:configurationBlock];
    NSURLSessionDataTask *dataTask = [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        JQNLogDebug(URLString, responseObject);
        success?success(task, responseObject):nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        JQNLogError(URLString, error);
        failure?failure(task, error):nil;
    }];
    
    return dataTask;
}

#pragma mark - #Private Methods

+ (AFHTTPSessionManager *)createHTTPSessionManagerWithConfiguration:(JQNetworkConfigBlock)configurationBlock
{
    NSParameterAssert(configurationBlock != nil);
    
    JQNetworkConfig* requestConfig = [[JQNetworkConfig alloc] init];
    if (configurationBlock) {
        configurationBlock(requestConfig);
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    if (requestConfig.requestSerializer) {
        manager.requestSerializer  = requestConfig.requestSerializer;
    }
    
    if (requestConfig.responseSerializer) {
        manager.responseSerializer  = requestConfig.responseSerializer;
    }
    
    return manager;
}

@end
